package com.example.mydy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.mydy.R;
import com.example.mydy.model.Achievement;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Date;

/**
 * 成就系统管理类
 */
public class AchievementManager {
    private static final String TAG = "AchievementManager";
    private static final String PREFS_NAME = "AchievementPrefs";
    private static final String KEY_USER_ACHIEVEMENTS = "user_achievements";
    
    private static AchievementManager instance;
    private SharedPreferences prefs;
    private Map<String, List<Achievement>> userAchievementsMap;
    private List<Achievement> availableAchievements;
    private final Gson gson = new Gson();
    private Context context;
    private String currentUsername;
    
    // 成就类型常量
    public static final String TYPE_LOGIN = "login";
    public static final String TYPE_TASK = "task";
    public static final String TYPE_REWARD = "reward";
    public static final String TYPE_ACTIVITY = "activity";
    public static final String TYPE_CONSECUTIVE = "consecutive";
    
    // 成就级别常量
    public static final int LEVEL_BRONZE = 1;
    public static final int LEVEL_SILVER = 2;
    public static final int LEVEL_GOLD = 3;
    
    // 成就解锁监听器
    public interface AchievementUnlockListener {
        void onAchievementUnlocked(Achievement achievement);
    }
    
    private AchievementUnlockListener unlockListener;
    
    // 私有构造函数，实现单例模式
    private AchievementManager(Context context) {
        this.context = context.getApplicationContext();
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        userAchievementsMap = new HashMap<>();
        loadUserAchievements();
        initAvailableAchievements();
    }
    
    /**
     * 获取AchievementManager实例
     */
    public static synchronized AchievementManager getInstance(Context context) {
        if (instance == null) {
            instance = new AchievementManager(context);
        }
        return instance;
    }
    
    /**
     * 设置成就解锁监听器
     */
    public void setAchievementUnlockListener(AchievementUnlockListener listener) {
        this.unlockListener = listener;
    }
    
    /**
     * 加载所有用户的成就数据
     */
    private void loadUserAchievements() {
        String achievementsJson = prefs.getString(KEY_USER_ACHIEVEMENTS, "");
        if (!achievementsJson.isEmpty()) {
            try {
                Type type = new TypeToken<Map<String, List<Achievement>>>() {}.getType();
                Map<String, List<Achievement>> loadedData = gson.fromJson(achievementsJson, type);
                if (loadedData != null) {
                    userAchievementsMap = loadedData;
                }
            } catch (Exception e) {
                Log.e(TAG, "加载成就数据失败: " + e.getMessage(), e);
                userAchievementsMap = new HashMap<>();
            }
        }
    }
    
    /**
     * 保存所有用户的成就数据
     */
    private void saveUserAchievements() {
        String achievementsJson = gson.toJson(userAchievementsMap);
        prefs.edit().putString(KEY_USER_ACHIEVEMENTS, achievementsJson).apply();
    }
    
    /**
     * 初始化所有可用成就
     */
    private void initAvailableAchievements() {
        availableAchievements = new ArrayList<>();
        
        // 登录成就
        availableAchievements.add(new Achievement("1", "初来乍到", "首次登录应用", Achievement.TYPE_LOGIN, LEVEL_BRONZE, 1, 10.0));
        availableAchievements.add(new Achievement("2", "忠实用户", "累计登录10天", Achievement.TYPE_LOGIN, LEVEL_SILVER, 10, 20.0));
        availableAchievements.add(new Achievement("3", "长期用户", "累计登录30天", Achievement.TYPE_LOGIN, LEVEL_GOLD, 30, 50.0));
        
        // 连续登录成就
        availableAchievements.add(new Achievement("4", "持之以恒", "连续登录3天", Achievement.TYPE_LOGIN, LEVEL_BRONZE, 3, 15.0));
        availableAchievements.add(new Achievement("5", "坚持不懈", "连续登录7天", Achievement.TYPE_LOGIN, LEVEL_SILVER, 7, 30.0));
        availableAchievements.add(new Achievement("6", "百折不挠", "连续登录30天", Achievement.TYPE_LOGIN, LEVEL_GOLD, 30, 100.0));
        
        // 任务成就
        availableAchievements.add(new Achievement("7", "初出茅庐", "提交第一个任务", Achievement.TYPE_TASK, LEVEL_BRONZE, 1, 10.0));
        availableAchievements.add(new Achievement("8", "任务达人", "累计提交10个任务", Achievement.TYPE_TASK, LEVEL_SILVER, 10, 30.0));
        availableAchievements.add(new Achievement("9", "任务大师", "累计提交50个任务", Achievement.TYPE_TASK, LEVEL_GOLD, 50, 100.0));
        
        // 悬赏成就
        availableAchievements.add(new Achievement("10", "悬赏新手", "完成第一个悬赏任务", Achievement.TYPE_TASK, LEVEL_BRONZE, 1, 10.0));
        availableAchievements.add(new Achievement("11", "悬赏能手", "累计完成10个悬赏任务", Achievement.TYPE_TASK, LEVEL_SILVER, 10, 30.0));
        availableAchievements.add(new Achievement("12", "悬赏王者", "累计完成30个悬赏任务", Achievement.TYPE_TASK, LEVEL_GOLD, 30, 100.0));
        
        // 活跃度成就
        availableAchievements.add(new Achievement("13", "活跃之星", "达到银牌活跃度", Achievement.TYPE_SOCIAL, LEVEL_BRONZE, 50, 20.0));
        availableAchievements.add(new Achievement("14", "活力四射", "达到金牌活跃度", Achievement.TYPE_SOCIAL, LEVEL_SILVER, 200, 50.0));
        availableAchievements.add(new Achievement("15", "活跃领袖", "达到钻石活跃度", Achievement.TYPE_SOCIAL, LEVEL_GOLD, 1000, 200.0));
    }
    
    /**
     * 获取指定用户的所有成就
     * @param username 用户名
     * @return 用户成就列表
     */
    public List<Achievement> getUserAchievements(String username) {
        if (!userAchievementsMap.containsKey(username)) {
            initUserAchievements(username);
        }
        return userAchievementsMap.get(username);
    }
    
    /**
     * 初始化用户成就
     * @param username 用户名
     */
    private void initUserAchievements(String username) {
        List<Achievement> userAchievements = new ArrayList<>();
        
        // 复制可用成就到用户成就列表
        for (Achievement achievement : availableAchievements) {
            try {
                // 创建深拷贝
                Achievement userAchievement = new Achievement(
                    achievement.getId(),
                    achievement.getName(),
                    achievement.getDescription(),
                    achievement.getType(),
                    achievement.getLevel(),
                    achievement.getTargetValue(),
                    achievement.getReward()
                );
                userAchievements.add(userAchievement);
            } catch (Exception e) {
                Log.e(TAG, "复制成就失败: " + e.getMessage(), e);
            }
        }
        
        userAchievementsMap.put(username, userAchievements);
        saveUserAchievements();
    }
    
    /**
     * 更新用户登录相关成就
     * @param username 用户名
     * @param totalLogins 总登录天数
     * @param consecutiveLogins 连续登录天数
     */
    public void updateLoginAchievements(String username, int totalLogins, int consecutiveLogins) {
        List<Achievement> userAchievements = getUserAchievements(username);
        List<Achievement> newUnlockedAchievements = new ArrayList<>();
        
        // 更新登录成就进度
        for (Achievement achievement : userAchievements) {
            if (achievement.getType() == Achievement.TYPE_LOGIN) {
                if (achievement.updateProgress(totalLogins)) {
                    newUnlockedAchievements.add(achievement);
                }
            }
        }
        
        // 保存更新
        saveUserAchievements();
        
        // 通知解锁的成就
        if (unlockListener != null) {
            for (Achievement achievement : newUnlockedAchievements) {
                unlockListener.onAchievementUnlocked(achievement);
            }
        }
    }
    
    /**
     * 更新用户任务相关成就
     * @param username 用户名
     * @param totalTasks 总任务数
     */
    public void updateTaskAchievements(String username, int totalTasks) {
        List<Achievement> userAchievements = getUserAchievements(username);
        List<Achievement> newUnlockedAchievements = new ArrayList<>();
        
        // 更新任务成就进度
        for (Achievement achievement : userAchievements) {
            if (achievement.getType() == Achievement.TYPE_TASK) {
                if (achievement.updateProgress(totalTasks)) {
                    newUnlockedAchievements.add(achievement);
                }
            }
        }
        
        // 保存更新
        saveUserAchievements();
        
        // 通知解锁的成就
        if (unlockListener != null) {
            for (Achievement achievement : newUnlockedAchievements) {
                unlockListener.onAchievementUnlocked(achievement);
            }
        }
    }
    
    /**
     * 更新用户悬赏相关成就
     * @param username 用户名
     * @param totalRewards 总悬赏任务数
     */
    public void updateRewardAchievements(String username, int totalRewards) {
        List<Achievement> userAchievements = getUserAchievements(username);
        List<Achievement> newUnlockedAchievements = new ArrayList<>();
        
        // 更新悬赏成就进度
        for (Achievement achievement : userAchievements) {
            if (TYPE_REWARD.equals(achievement.getType())) {
                if (achievement.updateProgress(totalRewards)) {
                    newUnlockedAchievements.add(achievement);
                }
            }
        }
        
        // 保存更新
        saveUserAchievements();
        
        // 通知解锁的成就
        if (unlockListener != null) {
            for (Achievement achievement : newUnlockedAchievements) {
                unlockListener.onAchievementUnlocked(achievement);
            }
        }
    }
    
    /**
     * 更新用户活跃度相关成就
     * @param username 用户名
     * @param monthlyActivity 月活跃度
     */
    public void updateActivityAchievements(String username, int monthlyActivity) {
        List<Achievement> userAchievements = getUserAchievements(username);
        List<Achievement> newUnlockedAchievements = new ArrayList<>();
        
        // 更新活跃度成就进度
        for (Achievement achievement : userAchievements) {
            if (achievement.getType() == Achievement.TYPE_SOCIAL) {
                if (achievement.updateProgress(monthlyActivity)) {
                    newUnlockedAchievements.add(achievement);
                }
            }
        }
        
        // 保存更新
        saveUserAchievements();
        
        // 通知解锁的成就
        if (unlockListener != null) {
            for (Achievement achievement : newUnlockedAchievements) {
                unlockListener.onAchievementUnlocked(achievement);
            }
        }
    }
    
    /**
     * 获取用户已解锁的成就数量
     * @param username 用户名
     * @return 已解锁成就数量
     */
    public int getUnlockedAchievementCount(String username) {
        List<Achievement> userAchievements = getUserAchievements(username);
        int count = 0;
        
        for (Achievement achievement : userAchievements) {
            if (achievement.isUnlocked()) {
                count++;
            }
        }
        
        return count;
    }
    
    /**
     * 获取用户成就完成百分比
     * @param username 用户名
     * @return 完成百分比 (0-100)
     */
    public int getAchievementCompletionPercentage(String username) {
        List<Achievement> userAchievements = getUserAchievements(username);
        if (userAchievements.isEmpty()) {
            return 0;
        }
        
        return getUnlockedAchievementCount(username) * 100 / userAchievements.size();
    }
    
    /**
     * 获取用户最近解锁的成就
     * @param username 用户名
     * @param limit 返回数量限制
     * @return 最近解锁的成就列表
     */
    public List<Achievement> getRecentUnlockedAchievements(String username, int limit) {
        List<Achievement> userAchievements = getUserAchievements(username);
        List<Achievement> unlockedAchievements = new ArrayList<>();
        
        // 筛选已解锁的成就
        for (Achievement achievement : userAchievements) {
            if (achievement.isUnlocked()) {
                unlockedAchievements.add(achievement);
            }
        }
        
        // 按解锁时间排序
        unlockedAchievements.sort((a1, a2) -> Long.compare(a2.getUnlockTime(), a1.getUnlockTime()));
        
        // 限制返回数量
        int count = Math.min(unlockedAchievements.size(), limit);
        return unlockedAchievements.subList(0, count);
    }
    
    /**
     * 为当前用户生成测试数据
     */
    public void generateTestData() {
        if (currentUsername == null) {
            currentUsername = "user1"; // 使用默认测试用户
        }
        
        // 获取用户成就列表
        List<Achievement> userAchievements = getUserAchievements(currentUsername);
        
        // 随机解锁一些成就作为测试
        Random random = new Random();
        int totalAchievements = userAchievements.size();
        int unlockedCount = random.nextInt(totalAchievements / 2) + 2; // 至少解锁2个成就
        
        // 清除已有进度
        for (Achievement achievement : userAchievements) {
            achievement.setCurrentValue(0);
            achievement.setUnlocked(false);
            achievement.setUnlockTime(0);
        }
        
        // 随机设置一些成就的进度
        for (int i = 0; i < totalAchievements; i++) {
            Achievement achievement = userAchievements.get(i);
            int progress = random.nextInt(achievement.getTargetValue() * 2);
            achievement.updateProgress(progress);
        }
        
        // 确保至少有指定数量的成就被解锁
        int currentUnlocked = 0;
        for (Achievement achievement : userAchievements) {
            if (achievement.isUnlocked()) {
                currentUnlocked++;
            }
        }
        
        // 如果解锁的成就不够，强制解锁一些
        while (currentUnlocked < unlockedCount) {
            int index = random.nextInt(totalAchievements);
            Achievement achievement = userAchievements.get(index);
            if (!achievement.isUnlocked()) {
                achievement.setCurrentValue(achievement.getTargetValue());
                achievement.setUnlocked(true);
                achievement.setUnlockTime(System.currentTimeMillis());
                currentUnlocked++;
            }
        }
        
        // 保存更新
        saveUserAchievements();
    }
    
    /**
     * 获取用户已解锁的成就数量
     */
    public int getUnlockedAchievementsCount() {
        if (currentUsername == null) {
            return 0;
        }
        
        List<Achievement> userAchievements = getUserAchievements(currentUsername);
        int count = 0;
        for (Achievement achievement : userAchievements) {
            if (achievement.isUnlocked()) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 获取用户已获得的总奖励点数
     */
    public int getTotalRewardPoints() {
        if (currentUsername == null) {
            return 0;
        }
        
        List<Achievement> userAchievements = getUserAchievements(currentUsername);
        int total = 0;
        for (Achievement achievement : userAchievements) {
            if (achievement.isUnlocked()) {
                total += achievement.getReward();
            }
        }
        return total;
    }
    
    /**
     * 获取用户成就完成百分比
     */
    public int getCompletionPercentage() {
        if (currentUsername == null) {
            return 0;
        }
        
        List<Achievement> userAchievements = getUserAchievements(currentUsername);
        if (userAchievements.isEmpty()) {
            return 0;
        }
        
        int unlockedCount = getUnlockedAchievementsCount();
        int totalCount = userAchievements.size();
        return (unlockedCount * 100) / totalCount;
    }
    
    /**
     * 检查所有成就
     * @param username 用户名
     */
    public void checkAllAchievements(String username) {
        // 这里添加逻辑来检查用户的所有成就状态
        // 例如可以从MockDataManager获取用户登录次数、任务数等，并更新相应成就
        this.currentUsername = username;
    }

    /**
     * 获取所有成就
     * @return 所有成就列表
     */
    public List<Achievement> getAllAchievements() {
        if (currentUsername == null) {
            return new ArrayList<>();
        }
        return getUserAchievements(currentUsername);
    }

    /**
     * 根据类型获取成就列表
     * @param type 成就类型
     * @return 指定类型的成就列表
     */
    public List<Achievement> getAchievementsByType(int type) {
        if (currentUsername == null) {
            return new ArrayList<>();
        }
        
        List<Achievement> userAchievements = getUserAchievements(currentUsername);
        if (type == Achievement.TYPE_ALL) {
            return userAchievements;
        }
        
        List<Achievement> filteredAchievements = new ArrayList<>();
        for (Achievement achievement : userAchievements) {
            if (achievement.getType() == type) {
                filteredAchievements.add(achievement);
            }
        }
        
        return filteredAchievements;
    }

    /**
     * 获取成就总数
     * @return 成就总数
     */
    public int getTotalAchievementsCount() {
        if (availableAchievements == null) {
            return 0;
        }
        return availableAchievements.size();
    }
} 